//
//  NetConfig.swift
//  kano
//
//  Created by Sophia on 2024/8/16.
//

import Foundation
import Moya
import KakaJSON

//Switch
let kEnvironment = 0
let kisEncrypt = 0
let kisConfusion = 0

let kRootPath = (kEnvironment == 0) ? "ant" : "swnt"
let kNormalPath = "/lend"
let kApplyPath = "/lend_step"
let kReportPath = "/lendData"
//let kNormalPath = "/swik"
//let kApplyPath = "/swik_step"
//let kReportPath = "/swikData"

//let kAppB = "kalong_b"
//let kAppC = "kalong_c"
//let kAppId = "kalion"
let kConfigUrl = "https://pastebin.com/raw/dJPBM2wg"


class NetConfig {
    
    static func readBaseUrl() -> String {
        if kEnvironment == 1 {
            //return "https://conn." + readDomin() + "/"
            return ""
        }
        return "https://ewdlgs.lendsafe.ng/"
    }

    static func readBaseWebUrl() -> String {
        if kEnvironment == 1 {
            return "https://conn." + readDomin() + "/index.html"
        }
        return "https://ewdlgs.fastbucks.ng/marble/index.html"
    }
    //默认使用.ng(git下发),访问不了用.com
    static func readDomin() -> String {
       if let domain = UserDefaults.standard.string(forKey: "kConfig") {
           return domain
       }
       return "lendsafecom.com"  //lendsafe.ng  lendsafecom.com
    }
    
    static func urlParam(_ parameters: [String: Any]? = nil) -> [String : Any] {
//        var urlParam: [String : Any] = ["ek":1,"c":kAppC,"b":kAppB,"binaryIndicator":KALanguage.readLanguage(),"appid":kAppId,"zuid":UIDevice.ka_UUID,"ch":KAAFTool.channel()]
        var urlParam: [String : Any] = ["ek":1,"bl":KALanguage.readLanguage(),"zuid":UIDevice.ka_UUID,"ch":KAAFTool.channel()]
        if (KAUserManager.shared.user.userid != 0) {
            urlParam.updateValue(KAUserManager.shared.user.userid, forKey: "u")
        }
        if (!KAUserManager.shared.user.userToken.isEmpty) {
            urlParam.updateValue(KAUserManager.shared.user.userToken, forKey: "t")
        }
        //apply port use
        if (!KAUserManager.shared.user.userGid.isEmpty) {
            urlParam.updateValue(KAUserManager.shared.user.userGid, forKey: "userGid")
        }
        //append parameters to url for get request
        if parameters != nil {
            for (key, value) in parameters! {
                urlParam.updateValue(value, forKey: key)
            }
        }
        if kisEncrypt == 1 {
            urlParam.updateValue("lend", forKey: "ed")  //encrypt
        }
        if kisConfusion == 0 {
            urlParam.updateValue("0", forKey: "confusion")
        }
        return urlParam
    }
    
    static func fullNormal(path: String, parameters:[String: Any]? = nil) -> String {
            let fullPath = kRootPath + kNormalPath + path
            return fullPath
    }
    static func fullApply(path: String, parameters:[String: Any]? = nil) -> String {
            let fullPath = kRootPath + kApplyPath + path
            return fullPath
    }
    static func fullReport(path: String, parameters:[String: Any]? = nil) -> String {
            let fullPath = kRootPath + kReportPath + path
            return fullPath
    }
    static func fullUrlStringForWeb(path: String) -> String {
        let fullPath = readBaseWebUrl() + path
        return fullPath
    }
    
    static func fullImgUrl(path: String) -> String {
        let fullPath = NetConfig.readBaseUrl() + kRootPath + "/lend_p/taskStatusCheck?captchaId=\(path)"
        return fullPath
    }
    
    

}




//let publicParamEndpointClosure = { (target: NormalService) -> Endpoint in
//    let url = target.baseURL.appendingPathComponent(target.path).absoluteString
//    let endpoint = Endpoint(url: url, sampleResponseClosure: { .networkResponse(200, target.sampleData)
//    }, method: target.method, task: target.task, httpHeaderFields: target.headers)
//    return endpoint.adding(newHTTPHeaderFields: ["x-platform" : "iOS", "x-interface-version" : "1.0", "otherKey": "otherValue"])
//}

let requestClosure = { (endpoint: Endpoint, closure: @escaping MoyaProvider<LoginAPI>.RequestResultClosure) in
    do {
        var request = try endpoint.urlRequest()
        request.timeoutInterval = kEnvironment == 1 ? 60 : 10
        closure(.success(request))
    } catch {
        print("error:", error)
    }
}

final class RequestHUDPlugin: PluginType {
    func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
        var mRequest = request
        //mRequest.timeoutInterval = kEnvironment == 1 ? 60 : 10
        
//        print("absoluteUrl:\(mRequest.url!.absoluteString)")
//        var absoluteString = mRequest.url!.absoluteString
//        
//        let path = target.path
//        let domin = target.baseURL.absoluteString
//        let string = domin + path + "?"
//        if let range = absoluteString.range(of: string) {
//            var partString = absoluteString.replacingCharacters(in: range, with: "")
////            print(partString)
//            partString = "lend=" + KAEncrypt.ka_encrypt(partString)
//            mRequest.url = URL(string: string + "\(partString)")
//        }
//        print("encodedUrl:\(mRequest.url!.absoluteString)")
        return mRequest
    }
    
    func willSend(_ request: RequestType, target: TargetType) {
        //other thread
//        DispatchQueue.main.async {
//            //动态域名配置和埋点上报 过滤不展示HUD
//            if target.path.contains(kReportPath) {return}
//            if target.baseURL.absoluteString.contains(kConfigUrl) {return}
//            UIViewController.ka_current().view.showLoading()
//        }
    }
    
    func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
        //main thread
//        if target.path.contains(kReportPath) {return}
//        if target.baseURL.absoluteString.contains(kConfigUrl) {return}
//        UIViewController.ka_current().view.hideLoading()
    }
}

let loggerPlugin = NetworkLoggerPlugin(configuration: .init(logOptions: [.requestHeaders, .requestBody, .successResponseBody]))



let loginProvider = MoyaProvider<LoginAPI>(requestClosure: requestClosure, plugins: [RequestHUDPlugin(), loggerPlugin])
let applyProvider = MoyaProvider<ApplyAPI>(requestClosure: requestClosure, plugins: [RequestHUDPlugin(), loggerPlugin])
let billProvider = MoyaProvider<BillAPI>(requestClosure: requestClosure, plugins: [RequestHUDPlugin(), loggerPlugin])
let reportProvider = MoyaProvider<ReportAPI>(requestClosure: requestClosure, plugins: [RequestHUDPlugin(), loggerPlugin])
